
import { loginWxAction } from "../../../../service/config"

import {
  articleDetail
} from "../../../../service/jb_article_service"
import {
  BIND_USER_ID
} from "../../../../service/base_service"
import {
  VIDEO_COVER,
} from "../../../../service/base_service"
import {
  voteReq,
  queryWorksVoteRecord,
  worksDetailReq
} from "../../../../service/jb_activity_service"
import moment from '../../../../tools/moment'
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showRulePopup: false,
    showRuleContent: `1.活动新注册用户，获得一票投票权利
    
    2.每个新用户只能为一个作品投票
    
    3.新用户点击作品投票按钮，注册后自动投票
    
    4.已注册用户无法投票`,
    menuTop: app.globalData.menuButton.top,
    menuHeight: app.globalData.menuButton.height,
    videoCoverUrl: VIDEO_COVER,
    videoUrl: "",
    id: "",
    userId: "",

    shareName: "",
    knoData: {
      title: "",
      synopsis: "",
      imageInput: '',
    },
    detailInfo: {},//详情
    userInfo: {},
    productDetail: {},
    worksId: null,
    dataList: [],
    page: 1,
    limit: 15,
    countTimestamp: 0,
    isShowLoading: false,
    isBottomShow: false,
    refreshFlag: false,
    // 分享相关：
    bindUserId: "",//绑定关系的userId,
    isScanEnter: false,//是否是扫码进来的
    isShare: false,//是否分享进来的
    isFriend: 0,
    isLogin: false,
    isCanVote: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let lanuchObj = wx.getLaunchOptionsSync();
    if (options.isFriend && options.isFriend == 1) {
      this.setData({
        isFriend: 1,
        worksId: options.worksId
      })
      wx.setStorageSync(BIND_USER_ID, options.userId);
    }
    if (lanuchObj.scene == 1155) {
      this.setData({
        isFriend: 0,
        isShare: true,
      })
    }
    if (this.data.isFriend == 1) {
      return;
    }
    if (options.worksId) {
      this.setData({
        worksId: options.worksId,
      })
    }
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    if (options.isShare) {
      this.setData({
        isScanEnter: false,
        isShare: true,
        bindUserId: options.userId,
      })
      wx.setStorageSync(BIND_USER_ID, options.userId);
      this.userWxLogin();

      return;
    }
    this.userWxLogin();

  },

  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickname || "";
        app.globalData.avatar = data.avatar || "";
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.userId = data.uid;
        this.setData({
          isLogin: data.isLogin
        })
        this.queryWorksDetail();
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);

    })
  },
  queryWorksDetail() {
    wx.showLoading()
    worksDetailReq(this.data.worksId).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        this.setData({
          detailInfo: res.data,
          countTimestamp: moment(res.data.vote.endTime).unix() || 0
        })
        if (res.data.products && res.data.products.length > 0) {
          this.setData({
            productDetail: res.data.products[0]
          })
        }
        this.queryWorksVoteRecord('refresh');
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      console.error("JJLog:worksDetailReq", err);
    })
  },



  //跳转到商品详情
  pushToProduct() {
    wx.navigateTo({
      url: '/shopMallPackage/pages/newStoreDetail/newStoreDetail?houseNumber=' + this.data.productDetail.id + "&type=normal",
    })
  },



  //视频播放失败回调;
  videoErrorCallback(e) {
    console.log("JJLog:视频播放失败:" + JSON.stringify(e));
  },
  //缓存中...
  videoWaiting(e) {
    console.log("JJLog:缓存zhong：" + JSON.stringify(e));
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.isLogin) {
      this.setData({
        isLogin: true,
      })
      if (app.globalData.voteSuccess) {
        //有投票成功：
        this.queryWorksDetail();
        this.queryWorksVoteRecord();
        app.globalData.voteSuccess = false;
      }
    }
    if (app.globalData.isCanVote) {
      this.setData({
        isCanVote: true,
      })
    }
  },


  //投票操作
  voteAction() {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login?type=' + 'vote' + "&voteId=" + this.data.detailInfo.voteId + "&worksId=" + this.data.worksId,
      })
      return;
    }
    // 登录过了且isCanVote是false的就retrun
    if (app.globalData.isLogin && !app.globalData.isCanVote) {
      return;
    }
    wx.showLoading();
    voteReq({
      voteId: this.data.detailInfo.voteId,
      worksId: this.data.worksId,
    }).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        app.globalData.isCanVote = false;
        this.setData({
          'detailInfo.isVote': true,
          isCanVote: false,
        })

        wx.showToast({
          title: '投票成功',
          icon: "success"
        })
        setTimeout(() => {
          this.queryWorksDetail();
          this.queryWorksVoteRecord();
        }, 2000)
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '投票失败',
        icon: "none"
      })
      console.error("JJLog:voteReq", err);
    })
  },



  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  //获取投票记录
  queryWorksVoteRecord(type) {
    wx.showLoading();
    queryWorksVoteRecord(this.data.page, this.data.limit, this.data.detailInfo.voteId, this.data.worksId).then(res => {
      wx.hideLoading();
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.dataList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          dataList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.page ? true : false,
        })

      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      if (this.data.page != 1) {
        this.setData({
          page: this.data.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.error('JJLog:queryWorksVoteRecord', err);
    })
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let path = "";
    path = "/featurePackage/pages/works/worksVideoDetail/worksVideoDetail?isShare=1" + "&userId=" + app.globalData.userId + "&worksId=" + this.data.detailInfo.id

    return {
      title: this.data.detailInfo.title + "为我投票吧！",
      imageUrl: this.data.detailInfo.coverPic,
      path: path
    }
  },
  showRulePopAction() {
    this.setData({
      showRulePopup: true,
    })
  },
  onShareTimeline: function () {
    return {
      title: this.data.detailInfo.title + "为我投票吧！",
      query: "isFriend=1" + "&userId=" + app.globalData.userId + "&worksId=" + this.data.detailInfo.id,
      imageUrl: this.data.detailInfo.coverPic,
    }
  },
  clickCenterPopupOverlay() {
    this.setData({
      showRulePopup: false,
    })
  },
})